package adminorg;




import org.vaadin.hene.popupbutton.PopupButton;

import com.vaadin.ui.AbstractSelect.AbstractSelectTargetDetails;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.DragAndDropWrapper.WrapperTargetDetails;
import com.vaadin.ui.Field;
import com.vaadin.ui.Form;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.Panel;
import com.vaadin.ui.Table;
import com.vaadin.ui.Table.TableDragMode;
import com.vaadin.ui.TextField;
import com.vaadin.ui.TreeTable;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.MenuBar.Command;
import com.vaadin.ui.MenuBar.MenuItem;
import com.vaadin.ui.Window.Notification;
import com.vaadin.ui.themes.Runo;
import com.vaadin.data.Item;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.event.DataBoundTransferable;
import com.vaadin.event.LayoutEvents.LayoutClickEvent;
import com.vaadin.event.LayoutEvents.LayoutClickListener;
import com.vaadin.event.dd.DragAndDropEvent;
import com.vaadin.event.dd.DropHandler;
import com.vaadin.event.dd.acceptcriteria.AcceptAll;
import com.vaadin.event.dd.acceptcriteria.AcceptCriterion;
import com.vaadin.data.util.filter.Compare.Greater;

public class OrgForm extends VerticalLayout {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 459515529234882084L;
	private VerticalLayout MainOrgForm = null;
	private VerticalLayout TVL = null;
	private HorizontalLayout OrgForm = null;
	private MenuBar OmenuBar = null;
	private ComboBox CompCombo = null;
	private HorizontalLayout MenuLayout = null;
	private Panel OrgPanel = null;
	private Panel ServPanel = null;
	private DatabaseHelper dbHelp = null; 
	private OrgSchema AL = null;
	private TreeTable TL = null;
	private HorizontalLayout ButPanel = null;
	private Button bAdd = null;
	private Button bEdit = null;
	private Button bDel = null;
	private Button bReDraw = null;
	private OrgItem OldItem = null;
	private int OldRoot = 0;
	private Form addForm = new Form();
	private boolean isEdit = false;
	private boolean isServVisible = false;
	private boolean bTreeTable = true;
	private Table Accounts = null;
	private ComboBox levelCombo = null;
	private PopupButton popupButton = null;
	private Command menuCommand = new Command() {
        /**
		 * 
		 */
		private static final long serialVersionUID = 8060615239086099770L;

		public void menuSelected(MenuItem selectedItem) {

			if (selectedItem.getText().equals(dbHelp.getWords("Refresh"))){
				try {
					dbHelp.getCompContainer().refresh();
					dbHelp.getCompAccContainer().refresh();
					dbHelp.getOrgschemaContainer().refresh();
					dbHelp.getOrgLevelContainer().refresh();
					if (!bTreeTable) paintOrgShem(); 
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
       	 	} else if (selectedItem.getText().equals("Развернуть полностью")){
        		OldRoot = 0;
        		paintOrgShem();
        	} else if (selectedItem.getText().equals("Редактировать")){
        		selectedItem.setText("Просмотр");
        		isEdit=true;
        		servPanelVisible(false);
        		if (bTreeTable) setButPanel(null); 
        	} else if (selectedItem.getText().equals("Просмотр")){
        		isEdit=false;
        		selectedItem.setText("Редактировать");
        		servPanelVisible(false);
        		if (bTreeTable) TVL.removeComponent(ButPanel);
        	} else if (selectedItem.getText().equals("Только Посты")){
        	  if (AL!=null)
        	  {
        		for (OrgItem P:AL.ITEMS.values()){
        			P.getName().setVisible(true);
        			P.getDeptName().setVisible(false);
        		}
        	  }
        	} else if (selectedItem.getText().equals("Только Подразделения")){
        		if (AL!=null)
        		{
        		  for (OrgItem P:AL.ITEMS.values()){
        			P.getName().setVisible(false);
        			P.getDeptName().setVisible(true);
        		  }
        		}
        	} else if (selectedItem.getText().equals("Полный")){
        	   if (AL!=null)
        	   {
        		for (OrgItem P:AL.ITEMS.values()){
        			P.getName().setVisible(true);
        			P.getDeptName().setVisible(true);
        		}
        	   }
        	} else if (selectedItem.getText().equals("Назначить пользователей")){
        		servPanelVisible(true);
        	} else if (selectedItem.getText().equals("Блок-схема")){
        		selectedItem.setText("Таблица");
        		bTreeTable=false;
        		paintOrgShem();
        	} else if (selectedItem.getText().equals("Таблица")){
        		selectedItem.setText("Блок-схема");
        		bTreeTable=true;
        		paintOrgShem();
        	}	
        }
	};    
	
	public OrgForm(DatabaseHelper dbHelper) throws Exception {
		MainOrgForm = new VerticalLayout();
		//MainOrgForm.setWidth("100%");
		MainOrgForm.setSizeFull();
		//START
		this.dbHelp = dbHelper;
		OrgForm = new HorizontalLayout();
		//OrgForm.setWidth("100%");
		OrgForm.setSizeFull();
		//TOP
		OmenuBar = new MenuBar();
		OmenuBar.setImmediate(false);
		//COMAPNYCOMBO
		CompCombo = new ComboBox();
		CompCombo.setImmediate(true);
		CompCombo.setNullSelectionAllowed(false);
		CompCombo.setContainerDataSource(dbHelp.getCompContainer());
		CompCombo.setItemCaptionPropertyId("name");
		//MENU/
		MenuLayout = new HorizontalLayout();
		if (dbHelp.isCompAccPropertySetForAnyCompany("isadmin")){
			OmenuBar.addItem("Редактировать",menuCommand);
			OmenuBar.addItem("Назначить пользователей", menuCommand);
		}
		OmenuBar.addItem("Печать", menuCommand);
		OmenuBar.addItem("Развернуть полностью", menuCommand);
		OmenuBar.addItem("Блок-схема", menuCommand);
		MenuItem View=OmenuBar.addItem("Вид", null);
		View.addItem("Полный", menuCommand);
		View.addItem("Только Посты",menuCommand);
		View.addItem("Только Подразделения",menuCommand);
		OmenuBar.addItem(dbHelp.getWords("Refresh"), menuCommand);
		//BUILD
		MenuLayout.addComponent(OmenuBar);
		MenuLayout.addComponent(CompCombo);
		MenuLayout.setSizeUndefined();
		MenuLayout.setImmediate(true);		
		MenuLayout.setWidth("100%");
		//CompCombo.setCaption("Организации");
		MenuLayout.setComponentAlignment(CompCombo, Alignment.TOP_RIGHT);
		MainOrgForm.addComponent(MenuLayout);
		MainOrgForm.addComponent(OrgForm);
		MainOrgForm.setExpandRatio(OrgForm, 1.0f);
		//OrgForm.addComponent(MenuLayout);
		OldRoot=0;
		addOrgListeners();
		CompCombo.select(dbHelp.getCompContainer().firstItemId());
		paintOrgShem();
		levelCombo=new ComboBox(dbHelp.getWords("LevelName"));
		levelCombo.setNullSelectionAllowed(false);
		dbHelp.getOrgLevelContainer().addSortingColumnAtBeginning("level", true);
		levelCombo.setContainerDataSource(dbHelp.getOrgLevelContainer());
		levelCombo.setItemCaptionPropertyId("name");
		addForm.setFormFieldFactory(new DefaultFieldFactory(){
			/**
			 * 
			 */
			private static final long serialVersionUID = -8513097931022211432L;

			@Override
			public Field createField(Item item, Object propertyId,
                    Component uiContext) {
				if (propertyId.equals("orgschema.level")) return levelCombo;
				if (propertyId.equals("orgschema.code")||
					propertyId.equals("orgschema.name")||
					propertyId.equals("orgschema.dept_name")||
					propertyId.equals("orgschema.docs")||
					propertyId.equals("orgschema.manager"))
				{
					Field field = super.createField(item, propertyId, uiContext);
					field.setWidth("243px");
					if (propertyId.equals("orgschema.code")){
						field.setRequired(true);
						field.setCaption("Код поста");
					}
					if (propertyId.equals("orgschema.name")){
						field.setRequired(true);
						field.setCaption("Наименование поста");
					}
					if (propertyId.equals("orgschema.dept_name")){
						field.setCaption("Наименование подразделения");
					}
					if (propertyId.equals("orgschema.docs")){
						field.setCaption("Документ");
					}
					if (propertyId.equals("orgschema.manager")){
						field.setCaption("Руководитель");
					}
					if (propertyId.equals("orgschema.level")){
						field.setCaption("Уровень");
					}
					if (field instanceof TextField) {
	                    ((TextField) field).setNullRepresentation("");
	                }
					return field;				
				} else return null;
			}
			
		});
		
	}
	
	private void paintOrgShem(){
		if (OrgPanel!=null){
			OrgForm.removeComponent(OrgPanel);
			OrgPanel=null;
		}
		if (ServPanel!=null){
			OrgForm.removeComponent(ServPanel);
			ServPanel=null;
		}
		OrgPanel = new Panel();
		OrgPanel.setSizeFull();
		OrgPanel.setScrollable(true);
		Object val = CompCombo.getValue();
		if (val==null) val = new Integer(1);
		if (val!=null)
		{
			if (bTreeTable) {
				try {
					TL = new TreeTable();
					//TL.setWidth("100%");
					TL.setSizeFull();
					TL.setContainerDataSource(dbHelp.views.getOrgschemaHierContainer());
					dbHelp.views.getOrgschemaHierContainer().setRoot(OldRoot);
					TL.setSelectable(true);
					TL.setStyleName(Runo.TABLE_SMALL);
					TL.setColumnCollapsingAllowed(true);
					TL.setColumnReorderingAllowed(true);
					TL.setImmediate(true);
					TL.setVisibleColumns(new Object[]{"orgschema.name","orgschema.code","orgschema.dept_name","compacc.name","orglevel.name"});
					TL.setColumnHeaders(dbHelp.getTranslatedStrings(new String[]{"Post","Code","Department","Name","Level"}));
					TVL = new VerticalLayout();
					//TVL.setWidth("100%");
					TVL.setSizeFull();
					TVL.addComponent(TL);
					OrgPanel.setContent(TVL);
					addAccDrop();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				AL = new OrgSchema(Integer.parseInt(val.toString()),OldRoot,dbHelp);
				OrgPanel.setContent(AL);
			}
		}
		//AL.addComponent(oc);
		OrgForm.addComponent(OrgPanel);	
		//return OrgPanel;		
		AddLayoutClick();
		ServPanel = new Panel();
		ServPanel.setWidth("150px");
		ServPanel.setHeight("100%");		
		ServPanel.setScrollable(true);
		servPanelVisible(isServVisible);
		try	{
			Accounts = new Table(null,dbHelp.getCompAccContainer());
			Accounts.setImmediate(true);
			Accounts.setVisibleColumns(new Object[]{("name")});
			Accounts.setSizeFull();
			Accounts.setColumnHeaders(dbHelp.getTranslatedStrings(new String[]{"Name"}));
			Accounts.setDragMode(TableDragMode.ROW);
			HorizontalLayout HL = new HorizontalLayout();
			HL.setSizeFull();
			HL.addComponent(Accounts);
			ServPanel.setContent(HL);
		}
		catch(Exception e)
		{
			AEHelper.logException(e,"Company Container");
		}
		
		OrgForm.addComponent(ServPanel);
		OrgForm.setComponentAlignment(ServPanel, Alignment.TOP_RIGHT);
		OrgForm.setExpandRatio(OrgPanel,1.0f);
		AddLayoutDrop();
	}
	
	private void servPanelVisible(boolean b){
		ServPanel.setVisible(b);
		isServVisible = b;
	}

	public VerticalLayout getOrgForm(){
		return MainOrgForm;
	};
	//

	private void setButPanel(OrgItem P){			
			ButPanel = new HorizontalLayout();
			bAdd 	 = new Button("+",ActionButtonClick);
			bEdit    = new Button("!",ActionButtonClick);
			bDel 	 = new Button("-",ActionButtonClick);
			bReDraw  = new Button("V",ActionButtonClick);
			ButPanel.addComponent(bAdd);
			ButPanel.addComponent(bEdit);
			ButPanel.addComponent(bDel);
			if (!bTreeTable) ButPanel.addComponent(bReDraw);
			bAdd.setVisible(isEdit);
			bDel.setVisible(isEdit);
			bEdit.setVisible(isEdit);
		if (!bTreeTable){
			popupButton = new PopupButton("");
			popupButton.setComponent(ButPanel);
			P.getL().addComponent(popupButton);
		} else {
			TVL.addComponent(ButPanel, 0);
		}
	};
	
	private Button.ClickListener ActionButtonClick = new Button.ClickListener() {			
		/**
		 * 
		 */
		private static final long serialVersionUID = -6302860062258222867L;

		@Override
		public void buttonClick(ClickEvent event) {
			try {
			  dbHelp.setCompanyId(CompCombo.getValue());
			} catch(Exception e)
			{
				AEHelper.logException(e, "Orgschema button click");
			}
			if (event.getButton().equals(bAdd)){
				if (bTreeTable){
					//TREE TABLE
					if (TL.getValue()==null) return;
					Integer OrgLevel = new Integer(TL.getContainerProperty(TL.getValue(), "orglevel.level").getValue().toString());
					Integer Pid = new Integer(TL.getValue().toString());
					try {
						dbHelp.views.getOrgschemaHierContainer().rollback();
					} catch (Exception e) {
						AEHelper.logException(e,"Orgschema before rollback");
					}
					try
					{
					Object tempItemId = dbHelp.views.getOrgschemaHierContainer().addItem();
					addForm.setItemDataSource(dbHelp.views.getOrgschemaHierContainer().getItem(tempItemId));
					}
					catch (Exception e)
					{
	                    AEHelper.logException(e,"Orgschema adding");					
					}
					try {
						dbHelp.getOrgLevelContainer().removeAllContainerFilters();
						dbHelp.getOrgLevelContainer().addContainerFilter(new Greater("level",OrgLevel));
						levelCombo.select(dbHelp.getOrgLevelContainer().firstItemId());
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					levelCombo.setVisible(true);
					addForm.getItemDataSource().getItemProperty("orgschema.pid").setValue(Pid);
					try {
						if (dbHelp.getOrgLevelContainer().size()>0)
							addForm.getItemDataSource().getItemProperty("orgschema.level").setValue(dbHelp.getOrgLevelContainer().firstItemId());
						else OrgForm.getWindow().showNotification("Отсутствуют уровни!", "Не заполнен справочник уровни!", Notification.TYPE_ERROR_MESSAGE);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 				
					addForm.getItemDataSource().getItemProperty("orgschema.manager").setValue(false);
					
					OrgForm.getWindow().addWindow(new formWindow("Добавление поста",addForm,
						new formWindow.Callback() {
						/**
							 * 
							 */
							private static final long serialVersionUID = 1285066485542627122L;

						@Override
						public void onDialogResult(boolean resultIsYes) {
							if (resultIsYes){
								try {
									addForm.commit();
									dbHelp.views.getOrgschemaHierContainer().commit();
									dbHelp.getOrgLevelContainer().removeAllContainerFilters();
								} catch (Exception e) {
									AEHelper.logException(e,"Orgschema apply");
									OrgForm.getWindow().showNotification("Error", e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
								}
							} else {
								try {
									dbHelp.views.getOrgschemaHierContainer().rollback();
								} catch (Exception e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						}	
					}));
				} else {
					//CLASIC
					try {
						dbHelp.views.getOrgschemaViewContainer().rollback();
					} catch (Exception e) {
						AEHelper.logException(e,"Orgschema before rollback");
					}
					try
					{
					Object tempItemId = dbHelp.views.getOrgschemaViewContainer().addItem();
					addForm.setItemDataSource(dbHelp.views.getOrgschemaViewContainer().getItem(tempItemId));
					}
					catch (Exception e)
					{
	                    AEHelper.logException(e,"Orgschema adding");					
					}								
					try {
						dbHelp.getOrgLevelContainer().removeAllContainerFilters();
						dbHelp.getOrgLevelContainer().addContainerFilter(new Greater("level",OldItem.getLevel()));
						levelCombo.select(dbHelp.getOrgLevelContainer().firstItemId());
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					levelCombo.setVisible(true);
					addForm.getItemDataSource().getItemProperty("orgschema.pid").setValue(OldItem.getId());
					try {
						if (dbHelp.getOrgLevelContainer().size()>0)
							addForm.getItemDataSource().getItemProperty("orgschema.level").setValue(dbHelp.getOrgLevelContainer().firstItemId());
						else OrgForm.getWindow().showNotification("Отсутствуют уровни!", "Не заполнен справочник уровни!", Notification.TYPE_ERROR_MESSAGE);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} 				
					addForm.getItemDataSource().getItemProperty("orgschema.manager").setValue(false);
					
					OrgForm.getWindow().addWindow(new formWindow("Добавление поста",addForm,
						new formWindow.Callback() {
						/**
							 * 
							 */
							private static final long serialVersionUID = 1285066485542627122L;
	
	
						@Override
							public void onDialogResult(boolean resultIsYes) {
								if (resultIsYes){
									try {
										addForm.commit();
										dbHelp.views.getOrgschemaViewContainer().commit();
										dbHelp.getOrgLevelContainer().removeAllContainerFilters();
									} catch (Exception e) {
										AEHelper.logException(e,"Orgschema apply");
										OrgForm.getWindow().showNotification("Error", e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
									}
									if ((OldItem!=null)&(popupButton!=null)){
										try {
											dbHelp.views.getOrgschemaViewContainer().rollback();
										} catch (Exception e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
										OldItem.getL().removeComponent(popupButton);
										popupButton = null;
										OldItem = null;
									}
									paintOrgShem();
								} else {
									try {
										dbHelp.views.getOrgschemaViewContainer().rollback();
									} catch (Exception e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}
							}
							
					}));
				}
			} else if (event.getButton().equals(bEdit)){
				if (bTreeTable){
					//TREE TABLE EDIT
					if (TL.getValue()==null) return;
					try {
						dbHelp.views.getOrgschemaHierContainer().rollback();
						dbHelp.views.getOrgschemaHierContainer().removeAllContainerFilters();
					} catch (Exception e) {
						AEHelper.logException(e,"Orgschema before rollback");
					}
					try
					{
					Object tempItemId = TL.getValue();
					addForm.setItemDataSource(dbHelp.views.getOrgschemaHierContainer().getItem(tempItemId));
					}
					catch (Exception e)
					{
	                    AEHelper.logException(e,"Orgschema adding");					
					}								
					levelCombo.setVisible(true);				
					OrgForm.getWindow().addWindow(new formWindow("Исправление поста",addForm,
						new formWindow.Callback() {	
							/**
							 * 
							 */
							private static final long serialVersionUID = -584747270209926390L;

							@Override
							public void onDialogResult(boolean resultIsYes) {
								if (resultIsYes){
									try {
										addForm.commit();
										dbHelp.views.getOrgschemaHierContainer().commit();
										dbHelp.getOrgLevelContainer().removeAllContainerFilters();
									} catch (Exception e) {
										AEHelper.logException(e,"Orgschema apply");
										OrgForm.getWindow().showNotification("Error", e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
									}
								} else {
									try {
										dbHelp.views.getOrgschemaHierContainer().rollback();
									} catch (Exception e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}
							}							
						}));
				} else {
					//CLASIC EDIT
					try {
						dbHelp.views.getOrgschemaViewContainer().rollback();
						dbHelp.views.getOrgschemaViewContainer().removeAllContainerFilters();
					} catch (Exception e) {
						AEHelper.logException(e,"Orgschema before rollback");
					}
					try
					{
					Object tempItemId = OldItem.getItemID();
					addForm.setItemDataSource(dbHelp.views.getOrgschemaViewContainer().getItem(tempItemId));
					}
					catch (Exception e)
					{
	                    AEHelper.logException(e,"Orgschema adding");					
					}								
					levelCombo.setVisible(true);				
					OrgForm.getWindow().addWindow(new formWindow("Исправление поста",addForm,
						new formWindow.Callback() {
						/**
							 * 
							 */
							private static final long serialVersionUID = 1285066485542627122L;
	
	
						@Override
							public void onDialogResult(boolean resultIsYes) {
								if (resultIsYes){
									try {
										addForm.commit();
										dbHelp.views.getOrgschemaViewContainer().commit();
										dbHelp.getOrgLevelContainer().removeAllContainerFilters();
									} catch (Exception e) {
										AEHelper.logException(e,"Orgschema apply");
										OrgForm.getWindow().showNotification("Error", e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
									}
									if ((OldItem!=null)&(popupButton!=null)){
										try {
											dbHelp.views.getOrgschemaViewContainer().rollback();
										} catch (Exception e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
										OldItem.getL().removeComponent(popupButton);
										popupButton = null;
										OldItem = null;
									}
									paintOrgShem();
								} else {
									try {
										dbHelp.views.getOrgschemaViewContainer().rollback();
									} catch (Exception e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}
							}
							
					}));
				}
			} else if(event.getButton().equals(bDel)){
				if (bTreeTable) {
					if (TL.getValue()==null) return;
					OrgForm.getWindow().addWindow(new confWindow("Удаление поста","Пост будет удален!".concat(TL.getValue().toString()),
							new confWindow.Callback() {
								/**
								 * 
								 */
								private static final long serialVersionUID = -3807395595819484360L;
		
								@Override
								public void onDialogResult(boolean resultIsYes) {
									if (resultIsYes){
										try {
											dbHelp.views.getOrgschemaHierContainer().removeItem(TL.getValue());
											dbHelp.views.getOrgschemaHierContainer().commit();
										} catch (Exception e) {
											AEHelper.logException(e,"Adding post");
											OrgForm.getWindow().showNotification("Error", e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
											try {
												dbHelp.views.getOrgschemaHierContainer().rollback();
											} catch (Exception e1) {
												// TODO Auto-generated catch block
												e1.printStackTrace();
											}
										}
									} else {
										try {
											dbHelp.views.getOrgschemaHierContainer().rollback();
										} catch (Exception e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									} 
								}							
							}));
				} else {
					OrgForm.getWindow().addWindow(new confWindow("Удаление поста","Пост будет удален!".concat(OldItem.getItemID().toString()),
						new confWindow.Callback() {
							/**
							 * 
							 */
							private static final long serialVersionUID = -3807395595819484360L;
	
							@Override
							public void onDialogResult(boolean resultIsYes) {
								if (resultIsYes){
									try {
										dbHelp.views.getOrgschemaViewContainer().removeItem(OldItem.getItemID());
										dbHelp.views.getOrgschemaViewContainer().commit();
									} catch (Exception e) {
										AEHelper.logException(e,"Adding post");
										OrgForm.getWindow().showNotification("Error", e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
										try {
											dbHelp.views.getOrgschemaViewContainer().rollback();
										} catch (Exception e1) {
											// TODO Auto-generated catch block
											e1.printStackTrace();
										}
									}
									if ((OldItem!=null)&(popupButton!=null)){
										OldItem.getL().removeComponent(popupButton);
										popupButton = null;
										OldItem = null;
									}
									paintOrgShem();
								} else {
									try {
										dbHelp.views.getOrgschemaViewContainer().rollback();
									} catch (Exception e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								} 
							}							
						}));
				}
			} else if(event.getButton().equals(bReDraw)){
				if ((OldItem!=null)&(popupButton!=null)){
					OldRoot = OldItem.getId(); 
					popupButton = null;
					OldItem = null;
				} else {
					OldRoot=0;
				}
				paintOrgShem();
			}
			
		}
	};
	
	private LayoutClickListener LayListener = new LayoutClickListener(){

		/**
		 * 
		 */
		private static final long serialVersionUID = -2137099106467368196L;

		@Override
		public void layoutClick(LayoutClickEvent event) {
			if ((OldItem!=null)&(popupButton!=null)){
				OldItem.getL().removeComponent(popupButton);
				popupButton = null;
				OldItem = null;
			}
			setButPanel((OrgItem) event.getComponent().getParent().getParent().getParent());
			OldItem = (OrgItem) event.getComponent().getParent().getParent().getParent();
		}
		
	};

	
	private void AddLayoutClick(){
	  if (AL!=null)
	  {
		for (OrgItem P:AL.ITEMS.values()){
			P.getL().addListener(LayListener);
		}
	  }
	}
	
	private void addAccDrop(){
		TL.setDropHandler(new DropHandler(){
			/**
			 * 
			 */
			private static final long serialVersionUID = 8187292346057304242L;

			@Override
			public void drop(DragAndDropEvent event) {
				// TODO Auto-generated method stub
				DataBoundTransferable t = (DataBoundTransferable) event.getTransferable();
				Object sourceItemId = t.getItemId();
				try {
					dbHelp.views.getOrgschemaHierContainer().rollback();
				} catch (Exception e) {
					AEHelper.logException(e,"Orgschema before rollback");
				}
				AbstractSelectTargetDetails  details =
				        (AbstractSelectTargetDetails ) event.getTargetDetails();
				Object targetItemId = details.getItemIdOver();
				try {
					dbHelp.views.getOrgschemaHierContainer().setPropertiesOfItem(targetItemId, "orgschema.accid", sourceItemId);
					dbHelp.views.getOrgschemaHierContainer().commit();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					try {
						dbHelp.views.getOrgschemaHierContainer().rollback();
					} catch (Exception e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
				}
				
			}

			@Override
			public AcceptCriterion getAcceptCriterion() {
				// TODO Auto-generated method stub
				return AcceptAll.get();
			}});
	}
	
	private void AddLayoutDrop(){
		if (AL!=null){
			for (OrgItem P:AL.ITEMS.values()){
				
				P.getLW().setDropHandler(new DropHandler(){
					/**
					 * 
					 */
					private static final long serialVersionUID = 8187292346057304242L;

					@Override
					public void drop(DragAndDropEvent event) {
						DataBoundTransferable t = (DataBoundTransferable) event.getTransferable();
						Object sourceItemId = t.getItemId();				
						try{
							dbHelp.views.getOrgschemaViewContainer().rollback();
						} catch (Exception ignored) {
		                	AEHelper.logException(ignored,"Orgchema rollback");
		                }
						try {
							WrapperTargetDetails details =
							        (WrapperTargetDetails) event.getTargetDetails();
							OrgItem tempItem = (OrgItem) details.getTarget().getParent().getParent();
							dbHelp.views.getOrgschemaViewContainer().setPropertiesOfItem(tempItem.getItemID()
									, "orgschema.accid", sourceItemId);
							dbHelp.views.getOrgschemaViewContainer().commit();
							dbHelp.views.getOrgschemaViewContainer().refresh();
							tempItem.setAccName(dbHelp.getCompAccContainer().getContainerProperty(sourceItemId, "name").getValue().toString());
						} catch (Exception e) {
							AEHelper.logException(e,"Orgschema apply");
							OrgForm.getWindow().showNotification("Error", e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
						}
						//paintOrgShem();
						//OrgForm.getWindow().showNotification("Пиф", "Пуф", Notification.TYPE_ERROR_MESSAGE);
					}

					@Override
					public AcceptCriterion getAcceptCriterion() {
						// TODO Auto-generated method stub
						return AcceptAll.get();
					}
					
				});
			}
		}
	}
	
	private void addOrgListeners(){
		dbHelp.addCompanyListener(new Property.ValueChangeListener() {
			/**
			 * 
			 */
			private static final long serialVersionUID = -357259282311643086L;

		@Override
		public void valueChange(ValueChangeEvent event) {
            Object id = CompCombo.getValue();	
            if (id!=null){
	            if (!(id instanceof Integer)){
	                	 id = Integer.parseInt(id.toString());
	                 }
	                 if (!id.equals(dbHelp.getCompanyId())){
	                	 try{
	                		 CompCombo.setValue(dbHelp.getCompanyId());
	                	 } catch (Exception e) {
	                	 }
	    
	                 }
                 }
			}
		});
		CompCombo.addListener(new Property.ValueChangeListener() {
			/**
			 * 
			 */
			private static final long serialVersionUID = 2965527967325979822L;

			@Override
			public void valueChange(ValueChangeEvent event) {
				Object id = CompCombo.getValue();
				if (!(id instanceof Integer))
				{
					id = Integer.parseInt(id.toString());
				}
				if (!id.equals(dbHelp.getCompanyId()))
				{
					try
					{
					   dbHelp.setCompanyId(id);					   
					}
					catch(Exception e)
					{
			        	AEHelper.logException(e,"Apply button click");
			        	OrgForm.getWindow().showNotification(dbHelp.getWords("ServerError"), e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
					}
				}
				OldRoot=0;
				paintOrgShem();
			}
		});
	}

}
